
const express = require('express')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const serverConfig = require('./config/serverConfig.js')
const serverAPI = require('./server/api/server/index.js')


/*mongoose 处理*/
mongoose.Promise = global.Promise
const db = mongoose.connection

mongoose.connect(serverConfig.TEST_DB_URL,{
  authSource:'admin',
  // useMongoClient:true,
  useNewUrlParser:true,
  useUnifiedTopology:true
})
db.on('error', function () {
  console.log('error opend!')
})
db.once('open', function () {
  console.log('database opend!')
})

/*express处理*/
const app = express()
const host = process.env.HOST || serverConfig.host
const port = process.env.PORT || serverConfig.port

app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())

app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  // 即在不同域名下发出的请求也可以携带 cookie 为了同一个session id
  res.header("Access-Control-Allow-Credentials",true)
  //Access-Control-Allow-Headers ,可根据浏览器的F12查看,把对应的粘贴在这里就行
  res.header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type');
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
  res.header('Access-Control-Request-Headers', 'Origin, X-Requested-With, content-Type, Accept, Authorization');
  // res.header('Content-Type', 'application/json;charset=utf-8');
  if (req.method.toLowerCase() == 'options') {
      res.sendStatus(200);  // 让options尝试请求快速结束
  } else {
      next();
  }
});

app.set('port', port)

// Import API Routes
app.use(`/server${serverConfig.api_path}`, serverAPI)
// API exmple
// http://localhost:8083/server/api/server/user/list

// Listen the server
app.listen(port, host)
console.log('Server listening on ' + host + ':' + port) 